/**
 * 全局http请求封装
 */
import store from '../../store/index.js'

const http = {
	request(url,data = {},method = "POST"){
		return new Promise((resolve, reject) => {
			uni.request({
				url:url,
				data:data,
				header:{
					'content-type':'application/x-www-form-urlencoded',
					'token': store.state.token
				},
				method:method,
				dataType:'json',
				success(res){
					if(res.statusCode == 200){
						if(res.data.code == 101){
							setTimeout(function(){
								uni.reLaunch({
									url: '../../login/login',
									fail:function(){
										uni.reLaunch({
											url: '../login/login',		
										})
									}
								});
							},1000);
						}
						resolve(res.data);	
					}else{
						//reject("网络错误");
						uni.showToast({ 
							icon: 'none',
							title: res.data.msg
						});
					}
				},
				fail(res){
					//reject("网络错误");
					uni.showToast({ 
						icon: 'none',
						title: res.data.msg
					});
				}
			})
		})
	},
	get(url){
		return this.request(url,{},"GET");
	},
	post(url,data){
		return this.request(url,data,"POST");
	},
	imgUpload(url,data){
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url:url,
				filePath:data,
				name: 'file',
				header:{
					'token': store.state.token
				},
				dataType:'json',
				success(res){
					if(res.statusCode == 200){
						res.data = JSON.parse(res.data);
						if(res.data.flag){
							resolve(res.data.data);	
						}else{
							//reject(res.data.msg);
							uni.showToast({ 
								icon: 'none',
								title: res.data.msg
							});
						}
					}else{
						//reject("网络错误");
						uni.showToast({ 
							icon: 'none',
							title: res.data.msg
						});
					}
				},
				fail(res){
					//reject("网络错误");
					uni.showToast({ 
						icon: 'none',
						title: res.data.msg
					});
				}
			})
		})
	}
}

export default http;